package com.hxzy.shop.commodity.controller;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.github.binarywang.utils.qrcode.QrcodeUtils;
import com.github.binarywang.wxpay.bean.ecommerce.enums.TradeTypeEnum;
import com.github.binarywang.wxpay.bean.order.WxPayNativeOrderResult;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.pagehelper.PageInfo;
import com.hxzy.shop.commodity.dto.req.RechargeReq;
import com.hxzy.shop.commodity.dto.resp.RechargeResp;
import com.hxzy.shop.commodity.service.MerchantPlugspaylogService;
import com.hxzy.shop.commodity.service.SysPlugsService;
import com.hxzy.shop.entity.MerchantPlugs;
import com.hxzy.shop.commodity.service.MerchantPlugsService;
import com.hxzy.shop.entity.MerchantPlugspaylog;
import com.hxzy.shop.entity.SysPlugs;
import com.hxzy.shop.vo.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
//import com.github.binarywang.wxpay.service.WxPayService;
import com.hxzy.shop.commodity.dto.req.PageRequst;
import io.swagger.annotations.ApiParam;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author qy
 * @Description: 处方单管理
 * @date:2021/8/10 11:31
 */


@RestController
@Api(tags = "处方单购买")
@RequestMapping("buyPre")
public class PrescriptionBuyController {

    //支付回调地址
    @Value("${call.address}")
    private String payCallBackAddress;
    @Resource
    private MerchantPlugsService merchantPlugsService;

    @Resource
    private MerchantPlugspaylogService merchantPlugspaylogService;

    @Resource
    private SysPlugsService sysPlugsService;

    //@Resource
    //private WxPayService wxService;

    @Value("${isDev}")
    private Boolean isDev;

    @ApiOperation("处方单使用详情")
    @PostMapping("/preUseInfo")
    public Result<MerchantPlugs> getPreInfo(@RequestBody PageRequst pageRequst) {
        MerchantPlugs resp = merchantPlugsService.getPreInfo(pageRequst.getPlugId());
        return Result.success(resp);
    }

    @ApiOperation("查询支付结果")
    @PostMapping("/loadPayResult")
    public Result<Boolean> loadPayResult(@RequestBody Map<String,Object> map) {
        String orderNo = (String) map.get("orderNo");
        MerchantPlugspaylog byId = merchantPlugspaylogService.getById(Long.valueOf(orderNo));
        if (ObjectUtil.isNotEmpty(byId)) {
            //查询微信支付流水号是否为空，为空表示支付未成功
            if (StringUtils.isBlank(byId.getPayNum())) {
                return Result.success(false);
            }
            return Result.success(true);
        }
        return Result.success(false);
    }

    @ApiOperation("获取商户充值列表")
    @PostMapping("/getRechargePage")
    public Result<PageInfo<MerchantPlugspaylog>> getRechargePage(@ApiParam(required = true, name = "pageRequst", value = "处方单购买记录分页参数对象")
                                                                 @RequestBody PageRequst pageRequst) {
        PageInfo<MerchantPlugspaylog> resp = merchantPlugspaylogService.getRechargePage(pageRequst);
        return Result.success(resp);
    }

    @ApiOperation("加载插件信息")
    @PostMapping("/loadPlugInfo")
    public Result<SysPlugs> loadPlugInfo(@RequestBody PageRequst pageRequst) {
        SysPlugs resp = sysPlugsService.loadPlugInfo(pageRequst.getPlugId());
        if (ObjectUtil.isEmpty(resp)) {
            return Result.success(null, "敬请期待");
        }
        return Result.success(resp);
    }

//    @ApiOperation("充值")
//    @PostMapping("/recharge")
//    public Result<RechargeResp> recharge(@ApiParam(readOnly = true, name = "rechargeReq", value = "充值参数对象")
//                                         @RequestBody RechargeReq rechargeReq,
//                                         HttpServletRequest req) throws Exception {
//        RechargeResp resp = merchantPlugsService.recharge(rechargeReq);
//
//        //调用微信支付接口
//        WxPayUnifiedOrderRequest request = new WxPayUnifiedOrderRequest();
//        request.setBody("处方单购买");
//        //订单号
//        request.setOutTradeNo(resp.getOrderNo());
//        //总金额
//        BigDecimal price = resp.getPrice();
//        Double v = price.doubleValue() * 100;
//        if (isDev){
//            //测试环境默认一分钱支付
//            request.setTotalFee(1);
//        }else {
//            request.setTotalFee(Integer.parseInt(String.valueOf(v.intValue())));
//        }
//
//        //获取本机ip
//        request.setSpbillCreateIp(req.getRemoteAddr());
//        //支付回调地址
//        request.setNotifyUrl(payCallBackAddress);
//        //支付类型
//        request.setTradeType(TradeTypeEnum.NATIVE.toString());
//        request.setProductId("12235413214070356458058");
//        //附加信息：添加购买处方单数量和商户id
//        Map<String, Object> map = new HashMap<>();
//        map.put("plugId", rechargeReq.getPlugId());
//        map.put("buyNum", rechargeReq.getNum());
//        map.put("merchantId", resp.getMerchantId());
//        request.setAttach(JSONObject.toJSONString(map));
//        //二维码有效期为一小时
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
//        Date date = new Date(System.currentTimeMillis() + 60 * 1000L);
//        request.setTimeExpire(sdf.format(date));
//        //调用微信支付接口
//        WxPayNativeOrderResult res = this.wxService.createOrder(request);
//
//        //返回支付二维码链接
//        byte[] qrCodeBytes = QrcodeUtils.createQrcode(res.getCodeUrl(), null);
//        String ercode = Base64.encodeBase64String(qrCodeBytes);
//
//        resp.setCodeUrl(ercode);
//        return Result.success(resp);
//    }

}
